var app = getApp();
var api = require('../../api.js');
var WxParse = require('../../wxParse/wxParse.js');
var util = require('../../utils/util.js');
var videoContextPrev;
var audio_context;
var timer;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    tabArr: {
      curHdIndex: 0,
      curBdIndex: 0
    },
    state1:0,
    flag2: true,
    buypop: true,
    teamx: true,
    teampop:true,
    show_modal: false,
    countDownList: [],
    actEndTimeList: [],
    video_password:'',
    video_id:'',
    play_time:0,//播放进度
    trywatch_status:0,//试看状态 1试看中
    is_trywatch: 0, //1已试看
    video_source_list:[],
    current_chapter:0,//当前选择章节
    urls: [
      '../../images/mall-goods002.jpg',
      '../../images/mall-goods001.jpg',
    ],
    kaituan_id:'',
    collectIcon: "../../images/ic-like000.png",
    audio_context:'',
    is_audio:0,
    pintuan_time:0,
    audioPlayStatus:0,
    can_play:0,
    detail_id:0,
    HiddenShare: true,
    HiddenShare1: true,
  },

  //点击选择团队人数
  select_team: function (e) {
    this.setData({
      state1: e.currentTarget.dataset.key,
    });
  },

 //点击创建团队
  fundTeam: function (e) {
    this.setData({
      kaituan_id: e.currentTarget.dataset.id,
      statete: e.currentTarget.dataset.key
    });
  },
  


//密码弹窗
  showpop2: function () {
    this.setData({ flag2: false })
  },
  //消失
  hidepop2: function () {
    this.setData({flag2: true})
  },

  //参团弹窗
  showteam: function () {
    this.setData({ teamx: false })
  },
  //消失
  hideteam: function () {
    this.setData({ teamx: true })
  },

  //建团弹窗
  create00: function () {
    this.setData({ teampop: false })
  },
  //消失
  hidefund: function () {
    this.setData({ teampop: true })
  },



//单独购买弹窗
  ownbuy: function () {
    this.setData({ buypop: false })
  },
  //消失
  ownbuyclose: function () {
    this.setData({ buypop: true})
  },

  //navbar，菜单切换
  tabFun: function (e) {
    //获取触发事件组件的dataset属性  
    var _datasetId = e.target.dataset.id;
    console.log("----" + _datasetId + "----");
    var _obj = {};
    _obj.curHdIndex = _datasetId;
    _obj.curBdIndex = _datasetId;
    this.setData({
      tabArr: _obj
    });
  },

  


  //评论图片
  showGallery(e) {
    const dataset = e.currentTarget.dataset
    const current = dataset.current
    const urls = this.data.urls

    $wuxGallery.show({
      current: current,
      urls: urls,
      [`delete`](current, urls) {
        urls.splice(current, 1)
        this.setData({
          urls: urls,
        })
        return !0
      },
      cancel: () => console.log('Close gallery')
    })
  },
  previewImage(e) {
    const dataset = e.currentTarget.dataset
    const current = dataset.current
    const urls = this.data.urls

    wx.previewImage({
      urls: [current],
    })
  },
  HiddenShareContent: function () {
    this.setData({
      HiddenShare: true
    })
  },

  popup1: function () {
    this.setData({
      HiddenShare: false
    })
  },

  GeneratePosters: function () {
    this.setData({
      HiddenShare: true
    })

  },
  ClosePosters: function () {
    this.setData({
      HiddenShare1: true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    if (options) {
      var tmp_options = wx.getStorageSync("tmp_options");
      if (tmp_options) {
        wx.setStorageSync("tmp_options", Object.assign(tmp_options, options))
      } else {
        wx.setStorageSync("tmp_options", options)
      }
      
    }
    if (options.scene) {
      var scene = decodeURIComponent(options.scene);
      scene = app.str2Obj(scene);
      this.setData({
        video_id: scene.video_id
      })
    }
    if (options.video_id){
      this.setData({
        video_id: options.video_id
      })
    }
    this.getVideoInfo();
    var page =this
    wx.getSystemInfo({
      success(res) {
        page.setData({
          sys_info: res,
          user_info:wx.getStorageSync('user_info')
        })
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var page =this
    if(page.data.video.style==1){
      page.pauseAudio();
      
    }
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var page = this
    if (page.data.video.style == 1) {
      audio_context.stop();
    }
    clearTimeout(timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var page = this
    var user = wx.getStorageSync('user_info');
    page.shareSuccess()
    return {
      title: page.data.video.share_title ? page.data.video.share_title : page.data.video.title,
      path:'/pages/course-detail/course-detail?video_id='+this.data.video_id+'&pid='+user.user_id,
      imageUrl: page.data.video.share_ico ? page.data.video.share_ico:this.data.video.pic_url,
      success: (res) => {
        
        console.log("转发成功", res);
      },
      fail: (res) => {
        console.log("转发失败", res);
      }
    }
  },

  //初始化获取视频信息
  getVideoInfo: function () {
    wx.showLoading({
      title: '加载中',
    })
    var page = this;
    var video_id = page.data.video_id;
    app.request({
      url: api.user.video,
      method: "post",
      data: {
        video_id: page.data.video_id,
      },
      success: function (res) {
        if (res.errcode == 0) {
          var video = res.data.video;
          if (res.data.status == 0) {
            wx.showModal({
              title: '提示',
              content: '该内容已下架',
              showCancel: false,
              confirmText: '去首页',
              success: function (res) {
                if (res.confirm) {
                  wx.redirectTo({
                    url: '/pages/index/index',
                  })
                }
              }
            })
          }

          else {
            
            var content = res.data.content + '<span> </span>'
            WxParse.wxParse("content", "html", content, page, 5);
            page.setData({
              money: res.data.money,
              video: res.data,
              //video_list: res.data.video_list,
              video_id: res.data.id,
              //video_pay: res.data.is_pay,
              //videoContext: wx.createLivePlayerContext("video-livePlayer")
            });
            //判断是音频类型
            if (res.data.style == 1 || res.data.style == '1'){
              page.createAudio();//创建音频容器
            }
            wx.setNavigationBarTitle({
              title: res.data.title,
            })
            page.getPintuanInfo();
          }
        } else if (res.errcode == 3005) {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.errmsg,
          })
          setTimeout(
            wx.navigateTo({
              url: '../index/index',
            }), 1000
          )
          return false;

        } else if (res.errcode == 5005) {
          wx.showModal({
            title: '提示',
            content: '该内容已下架',
            showCancel: false,
            confirmText: '去首页',
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '/pages/index/index',
                })
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })
        }
      },
      complete: function (res) {
        wx.hideLoading()
      }
    });



  },

  //获取拼团列表
  getPintuanInfo:function(){
    var page = this;
    var video_id = page.data.video_id;
    app.request({
      url: api.order.video_kaituan_list,
      method: "post",
      data: {
        video_id: video_id,
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            creatteam:res.data
          })
          //拼团时间
          if(res.data.length>0){
            var timestamp = Date.parse(new Date());
            timestamp = timestamp / 1000;
            let pintuan_time = parseInt(res.data[0].end_time) - timestamp;
            console.log(res.data[0].end_time)
            page.setData({
              pintuan_time: pintuan_time,
            })
            page.setCountDown();
          }
          page.getJointuanInfo();
        }
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },

  //获取可参团列表
  getJointuanInfo: function () {
    var page = this;
    var video_id = page.data.video_id;
    app.request({
      url: api.order.video_joinpintuan_list,
      method: "post",
      data: {
        video_id: video_id,
      },
      success: function (res) {

        if (res.errcode == 0) {
          console.log(typeof (res.data))
          if(typeof(res.data)=="object"){
            page.setData({
              team: res.data
            });
          }else{
            page.setData({
              detail_id: res.data
            })
            
          }
          page.loadComment();
        }
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },

  //开团
  kaituan: function () {
    var page = this;
    var video_id = page.data.video_id;
    if (!page.data.kaituan_id){
      wx.showToast({
        title: '请选择开团规模',
        icon:'none'
      })
      return false;
    }
    wx.showLoading({
      title: '提交中',
    })
    app.request({
      url: api.order.video_kaituan,
      method: "post",
      data: {
        pintuan_id:page.data.kaituan_id,
        video_id: video_id,
      },
      success: function (res) {

        if (res.errcode == 0) {
          //订单支付
          app.request({
            url: api.order.get_pay_data,
            method: "post",
            data: {
              order_id: res.data.order_id,
              pay_type: 'WECHAT_PAY'
            },
            success: function (result) {
              wx.hideLoading();
              if (result.errcode == 0) {
                var pay_data = result.data;
                wx.requestPayment({
                  timeStamp: pay_data.timeStamp,
                  nonceStr: pay_data.nonceStr,
                  package: pay_data.package,
                  signType: pay_data.signType,
                  paySign: pay_data.paySign,
                  success: function (pres) {
                    wx.showToast({
                      title: '订单支付成功',
                      icon: 'success'
                    });
                    page.hidefund();
                    wx.navigateTo({
                      url: '../pingou-detail/pingou-detail?detail_id=' + res.data.detail_id,
                    })
                  },
                  fail: function (res) {
                    wx.showToast({
                      title: '订单未支付',
                      image: '/images/icon-warning.png'
                    });
                  }
                });
              } else {
                wx.hideLoading();
                wx.showModal({
                  title: '提示',
                  content: result.errmsg,
                  showCancel: false
                });
              }
            }
          });
        }else{
          wx.showModal({
            title: '提示',
            content: res.errmsg,
          })
        }
      },
      complete: function (res) {
        wx.hideLoading()
      }
    });
  },

  //加载评论
  loadComment: function (id) {
    var page = this;
    //is_loading_more = true;
    app.request({
      url: api.user.comment_list,
      method:'POST',
      data: {
        video_id: page.data.video_id,
        page: 1
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            comment_list: res.data.list,
            comment_page: res.data.page_info,
          });
        } else {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
          })
        }
      },
      fail: function (res) {
        wx.showModal({
          title: '警告',
          content: res.msg,
          showCancel: false
        })
      },
      complete: function () {
        wx.hideLoading();
        //is_loading_more = false;
      }
    });
  },


  //根据密码获取视频
  getVideoByPassword: function () {
    var page = this;
    var video_id = page.data.video_id;
    if (!page.data.video_password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    wx.showLoading({
      title: "提交中"
    });
    app.request({
      url: api.user.video,
      method: "post",
      data: {
        video_id: video_id,
        password: page.data.video_password
      },
      success: function (res) {
        console.log(res.data);
        if (res.errcode == 0) {
          var video = page.data.video;

          if (res.data.AUTH == false) {
            wx.showToast({
              title: "密码错误",
              icon: 'none',
              duration: 2000
            });
          } else {

            video.AUTH = true;
            page.setData({
              video: video
            });
            wx.showToast({
              title: "密码正确",
              icon: 'success',
              duration: 1000
            })
          }
        } else {
          wx.showToast({
            title: "错误",
            icon: 'none',
            duration: 2000
          })
        }
      }
    })

  },

  //购买完成获取视频
  getVideoByBuy: function () {
    var page = this;
    var video_id = page.data.video_id;
    app.request({
      url: api.user.video,
      method: "post",
      data: {
        video_id: video_id,
      },
      success: function (res) {
        if (res.data.errcode == 0) {
          var video = page.data.video;
          video.video_url = res.data.data.video_url;
          page.setData({
            video: video
          })
        } else {
          wx.showToast({
            title: res.data.errmsg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })

  },

  //购买视频
  buyVideo: function () {
    var page = this;
    var video = page.data.video;
    wx.showModal({
      title: '提示',
      content: '是否购买？',
      success: function (e) {
        if (e.confirm) {
          wx.showLoading({
            title: '提交中',
          });

          app.request({
            url: api.order.video,
            method: 'POST',
            data: {
              video_id: video.id,
              //price: page.data.video_pay.price
            },
            success: function (res) {
              console.log(res);
              if (res.errcode == 0) {
                app.request({
                  url: api.order.get_pay_data,
                  method: 'POST',
                  data: {
                    order_id: res.data.order_id,
                    pay_type: 'WECHAT_PAY'
                  },
                  success: function (result) {
                    wx.hideLoading();
                    if (result.errcode == 0) {
                      var pay_data = result.data;
                      wx.requestPayment({
                        timeStamp: pay_data.timeStamp,
                        nonceStr: pay_data.nonceStr,
                        package: pay_data.package,
                        signType: pay_data.signType,
                        paySign: pay_data.paySign,
                        success: function (res) {
                          wx.showToast({
                            title: '订单支付成功',
                            icon: 'success'
                          });
                          page.setData({
                            buypop:true
                          });
                          setTimeout(function () {
                            page.getVideoByBuy();
                          }, 2000)
                        },
                        fail: function (res) {
                          wx.showToast({
                            title: '订单未支付',
                            image: '/images/icon-warning.png'
                          });
                        }
                      });
                    } else {
                      wx.showModal({
                        title: '提示',
                        content: result.msg,
                        showCancel: false
                      });
                    }
                  }
                });
              } else {
                wx.showModal({
                  title: '警告',
                  content: res.msg,
                  showCancel: false
                })
              }
            }
          });
        }
      }
    })
  },

  //密码输入
  getPassword: function (e) {
    console.log(e);
    this.setData({
      video_password: e.detail.value
    });
  },

  //提交密码
  submitpassword: function (e) {
    this.getVideoByPassword(this.data.video_password);
    this.hidepop2();
  },

  //购买vip
  buyVip: function () {
    wx.navigateTo({
      url: '/pages/member/member',
    })
  },

  //回到首页
  backIndex: function (e) {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  //试看
  tryWatch:function(){
    var page =this
    this.setData({
      trywatch_status:1,
      is_trywatch:1
    })
    if(this.data.is_audio==1){
      audio_context.src = page.data.video.chapter[page.data.current_chapter].video_url;
    }
  },
  //视频播放中
  timeupdate:function(e){
    var page=this
    var time = page.data.play_time
    page.setData({
      play_time: time+0.25
    })
    //试看
    if (page.data.trywatch_status==1 || !page.data.video.AUTH){
      if (e.detail.currentTime>=180){
        page.setData({
          trywatch_status: 0
        })
        if(page.data.is_audio==1){
          page.stopAudio();
        }else{
          videoContextPrev = wx.createVideoContext('video');
          console.log(videoContextPrev);
          videoContextPrev.exitFullScreen()
          videoContextPrev.seek(0)
          // videoContextPrev.src="";
          videoContextPrev.stop() 
        }
        
      }
    }
    
  },

  //切换章节
  //章节选择
  select_date: function (e) {
    var page =this
    if (page.data.video.chapter[e.currentTarget.dataset.key].type == 1) {
      wx.navigateTo({
        url: '../live-class/live-class?video_id=' + page.data.video.chapter[e.currentTarget.dataset.key].live_id + '&for_video_id=' + page.data.video_id,
      })
    }
    if (page.data.video.AUTH == false) {
      wx.showToast({
        title: '请先获取授权',
        icon:'none',
      })
      return false
    }
    if (page.data.current_chapter != e.currentTarget.dataset.key){
      
      page.setData({
        state1: e.currentTarget.dataset.key,
        current_chapter: e.currentTarget.dataset.key
      });
      
      //视频
      if (page.data.video.style == 0 || page.data.video.style == '0') {
        videoContextPrev = wx.createVideoContext('video');
        videoContextPrev.seek(0)
        videoContextPrev.pause()
      }
      //音频
      if (page.data.video.style == 1 || page.data.video.style == '1') {
        page.setData({
          audioPlayStatus: 0
        })
        audio_context.stop();
        audio_context.src = page.data.video.chapter[page.data.current_chapter].video_url;
        audio_context.title = page.data.video.chapter[page.data.current_chapter].name;
      }
      
    }
  },

  //收藏事件
  collect: function () {
    var page = this;
    app.request({
      url: api.user.collect,
      method: 'POST',
      data: {
        video_id: page.data.video_id
      },
      success: function (res) {
        if (res.errcode == 0) {
          var video_tmp = page.data.video;
          if (page.data.video.collect == true) {
            video_tmp.collect = false;
            page.setData({
              video: video_tmp
            });
            wx.showToast({
              title: '取消收藏',
              icon: 'success'
            });
          } else {
            video_tmp.collect = true;
            page.setData({
              video: video_tmp
            });
            wx.showToast({
              title: '收藏成功',
              icon: 'success'
            });
          }
        } else {
          wx.showModal({
            title: '警告',
            content: res.msg,
            showCancel: false
          })
        }
      }
    });
  },

  //创建音频容器
  createAudio:function(){
    var page =this
    
    let audioContext = wx.getBackgroundAudioManager();
    // if(page.data.video.AUTH==true){
    //   audioContext.src = page.data.video.chapter[page.data.current_chapter].video_url;
    // }
   
    audioContext.title = page.data.video.chapter[page.data.current_chapter].name;
    audioContext.coverImgUrl = page.data.video.pic_url;
    
    console.log(audioContext);
    audioContext.onTimeUpdate(page.timeupdate)
    audioContext.onCanplay(page.canPlay);
    audioContext.onPause(page.onPauseAudio);
    audioContext.onStop(page.onStopAudio);
    audioContext.onEnded(page.endPlay);
    audioContext.onPlay(page.onPalyAudio);
    
    audio_context = audioContext
    
    page.setData({
      is_audio:1,
    })
  },
  canPlay:function(){
    var page = this
    wx.hideLoading();
    page.setData({
      can_play:1
    })
  },
  endPlay:function(e){
    var page = this
    wx.showToast({
      title: '播放结束',
    });
    page.stopAudio();
  },
  onPalyAudio:function(){
    this.setData({
      audioPlayStatus: 1
    })
  },
  onPauseAudio:function(){
    this.setData({
      audioPlayStatus: 0
    })
  },
  onStopAudio: function () {
    this.setData({
      audioPlayStatus: 0
    })
  },
  //暂停音频
  pauseAudio:function(){
    var page = this
    audio_context.pause()
    page.setData({
      audioPlayStatus:0
    })
  },
  //播放音频
  playAudio: function () {
    var page = this
    console.log(audio_context);
    audio_context.play();
    if(!audio_context.src){
      audio_context.src = page.data.video.chapter[page.data.current_chapter].video_url;
    }
    console.log(audio_context);

    if(page.data.can_play==0){
      wx.showLoading({
        title: '缓冲中',
      })
    }
    
  },
  //停止音频
  stopAudio:function(){
    var page = this
    audio_context.stop()
    page.setData({
      audioPlayStatus: 0
    })
  },
  //分享成功
  shareSuccess:function(){
    var page =this
    app.request({
      url: api.video.share_success,
      method: 'POST',
      data: {
        video_id: page.data.video_id
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.getVideoInfo()
        } else {
          wx.showModal({
            title: '警告',
            content: res.msg,
            showCancel: false
          })
        }
      }
    });
  },
  //邀请好友
  sharePartner:function(){
    wx.navigateTo({
      url: '../pingou-detail/pingou-detail?detail_id='+this.data.detail_id,
    })
  },
  /**
   * 倒计时
   */
  setCountDown: function () {
    let page = this
    let time = 1;
    let pintuan_time = page.data.pintuan_time
    pintuan_time -= time;

    if (pintuan_time > 0) {
      let formatTime = page.getFormat(pintuan_time);
      let countDown = `${formatTime.dd}天${formatTime.hh}:${formatTime.mm}:${formatTime.ss}`;
      page.setData({
        pintuan_time: pintuan_time,
        formatTime: formatTime,
        countDown: countDown
      });
      timer = setTimeout(page.setCountDown, 1000);
    }

  },

  /**
   * 格式化时间
   */
  getFormat: function (msec) {
    let ss = parseInt(msec);
    // let ms = parseInt(msec % 1000);
    let mm = 0;
    let hh = 0;
    let dd = 0;
    if (ss > 60) {
      mm = parseInt(ss / 60);
      ss = parseInt(ss % 60);
      if (mm > 60) {
        hh = parseInt(mm / 60);
        mm = parseInt(mm % 60);
        if (hh > 24) {
          dd = parseInt(hh / 24);
          hh = parseInt(hh % 24);
        }
      }
    }
    ss = ss > 9 ? ss : `0${ss}`;
    mm = mm > 9 ? mm : `0${mm}`;
    hh = hh > 9 ? hh : `0${hh}`;
    dd = dd > 9 ? dd : `0${dd}`;
    return {
      ss,
      mm,
      hh,
      dd
    };
  },

  createHaiBao: function () {
    wx.showLoading({
      title: '创建中',
    })
    var page = this;
    app.request({
      url: api.video.share_qrcode,
      method: "post",
      data: {
        id: page.data.video_id
      },
      success: function (res) {
        if (res.errcode == 0) {
          page.setData({
            haibao: res.data
          })
          page.createNewImg()
        } else {
          wx.showModal({
            title: '提示',
            content: res.errmsg,
            showCancel: false
          })
        }
      },
      complete: function (res) {
        wx.hideLoading();
      }
    });
  },

  /**
   * 生成二维码
   */

  createNewImg: function () {
    wx.showLoading({
      title: '生成中...',
    })
    var that = this;
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    that.GeneratePosters()
    var context = wx.createCanvasContext('mycanvas');
    // const ctx = canvas.getContext('2d');
    context.setFillStyle("#fff");
    context.fillRect(0, 0, width, height);


    //昵称
    context.setFontSize(15);
    context.setFillStyle('#000');
    context.setTextAlign('left');
    context.fillText(wx.getStorageSync('user_info').nickName, 80 * per_width, 60 * per_height, 280 * per_width);
    context.stroke();

    //昵称
    context.setFontSize(13);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText('我发现一个精彩的课程，快来看!', 80 * per_width, 90 * per_height, 280 * per_width);
    context.stroke();

    var text = that.data.video.title;
    //标题
    context.setFontSize(14);
    context.setFillStyle('#333');
    context.setTextAlign('left');


    var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < 335 * per_width) {
        temp += chr[a];
      } else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);
    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < 220 * per_width) {
          test += rowPart[a];
        } else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..." //这里只显示两行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      context.fillText(row[b], 20 * per_width, (560 + b * 24) * per_height, 335 * per_width);
    }

    //提示
    context.setFontSize(13);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText('长按识别图中的小程序码', 180 * per_width, 640 * per_height, 280 * per_width);
    context.stroke();
    //提示
    context.setFontSize(13);
    context.setFillStyle('#666');
    context.setTextAlign('left');
    context.fillText('查看课程详情', 180 * per_width, 680 * per_height, 280 * per_width);
    context.stroke();
    that.setLogo(context); //绘制头像 
    // context.draw();
    context.fill()
    context.closePath()


  },
  darwAvatarArc: function (ctx, src, x, y, w, h = w) {
    ctx.save();
    ctx.beginPath()
    ctx.arc(x + w / 2, y + h / 2, w / 2, 0, Math.PI * 2, false);
    ctx.clip()
    ctx.drawImage(src, x, y, w, h);
    ctx.restore()
    ctx.draw(true)
  },

  setLogo(ctx) {
    var that = this;
    //that.darwAvatarArc(context, src, 50, 90, 45, 45);
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    var avatarurl_width = 45 * per_width; //绘制的头像宽度
    var avatarurl_heigth = 45 * per_width; //绘制的头像高度
    var avatarurl_x = 20 * per_width; //绘制的头像在画布上的位置
    var avatarurl_y = 40 * per_height; //绘制的头像在画布上的位置
    wx.downloadFile({
      url: that.data.haibao.headimg,
      success: function (res) {
        ctx.save()
        ctx.beginPath() //开始绘制
        ctx.setFillStyle('#fff')
        //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
        ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
        //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因    
        ctx.clip()
        ctx.drawImage(res.tempFilePath, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth);
        ctx.closePath()
        //恢复之前保存的绘图上下文 恢复之前保存的绘图上下文即状态 还可以继续绘制
        ctx.restore()
        //可将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中                                         
        that.setBanner(ctx)
      },
      fail(err) {
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })

      }
    })
  },


  setBanner: function (ctx) {
    var that = this;
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    wx.downloadFile({
      url: that.data.video.pic_url,
      success: function (res) {
        ctx.drawImage(res.tempFilePath, 20 * per_width, 120 * per_height, 335 * per_width, 335 * per_width);
        ctx.save();
        ctx.restore();
        //绘制奖品名字
        that.setQrcode(ctx)
      },
      fail(err) {
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })
      }
    })
  },
  setQrcode(ctx) {
    var that = this;
    var width = that.data.sys_info.windowWidth;
    var height = that.data.sys_info.windowHeight;
    var per_width = width / 375;
    var per_height = height / 750;
    var avatarurl_width = 90 * per_width; //绘制的头像宽度
    var avatarurl_heigth = 90 * per_width; //绘制的头像高度
    var avatarurl_x = 60 * per_width; //绘制的头像在画布上的位置
    var avatarurl_y = 600 * per_height; //绘制的头像在画布上的位置
    wx.downloadFile({
      url: that.data.haibao.qr_img,
      success: function (res) {
        ctx.save()
        ctx.beginPath()
        ctx.setFillStyle('#dcdcdc')
        ctx.arc(avatarurl_width / 2 + avatarurl_x, avatarurl_heigth / 2 + avatarurl_y, avatarurl_width / 2, 0, Math.PI * 2, false);
        ctx.clip()
        ctx.drawImage(res.tempFilePath, avatarurl_x, avatarurl_y, avatarurl_width, avatarurl_heigth);
        ctx.closePath()
        ctx.restore()
        that.showImg(ctx);
      },
      fail(err) {
        console.log(err);
        wx.hideLoading();
        wx.showToast({
          title: err.errMsg,
          icon: 'none'
        })

      }
    })
  },
  showImg(ctx) {
    var that = this;
    that.setData({
      HiddenShare1: false
    })
    ctx.draw(false, function (e) {
      console.log('绘制成功');
      that.saveTempCavans();

    })
  },
  saveTempCavans: function (e) {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      fileType: 'jpg',
      quality: 1,
      success: function (res) {
        // 获得图片临时路径
        that.setData({
          imagePath: res.tempFilePath,
          canvasHidden: true,
          HiddenShare1: false
        })
        that.imageTempPath = res.tempFilePath;
        that.imgSrc = that.imageTempPath;
        setTimeout(function () {
          wx.hideLoading();
        }, 200)
      },
      fail: function (res) {
        setTimeout(function () {
          that.saveTempCavans();
        }, 1000)
      }
    })
  },

  //点击保存到相册
  baocun: function () {
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imagePath,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 该隐藏的隐藏 */
              that.setData({
                HiddenShare1: true
              })
            }
          },
          fail: function (res) {
            console.log(res)
          }
        })
      }
    })
  },

  

})